﻿using System.Reflection;
using WYJ.SDK.Core;

internal class Handler
{
    public static Dictionary<string, Action<string[]>> MethodDic { get; set; }

    public static void Invoke(string methodName, params string[] args)
    {
        if(methodName.StartsWith("-"))
        {
            if (App.Setting.CommandMap.ContainsKey(methodName)) methodName = App.Setting.CommandMap[methodName];
            else methodName = "help";
        }
        if (MethodDic.TryGetValue(methodName.ToLower(), out var method))
        {
            method(args);
        }
        else
        {
            Help(args);
        }
    }

    static Handler()
    {
        ReLoad(null);
    }

    private static void NewApp(string[] a)
    {
        DirectoryInfo[] dirs = App.TemplateDir.GetDirectories();
        dirs = dirs.Concat(App.Setting.TemplatePrograms.Select(dir=> new  DirectoryInfo(dir))).ToArray();
        var dirNo_ = WYJConsole.Select("请选择项目模板", dirs.Select(dir => dir.Name).ToArray());
        var dir = dirs[dirNo_];
        foreach (var file in dir.CopyTo(Environment.CurrentDirectory))
        {
            Console.WriteLine($"{file.FullName} 复制成功。");
        };
    }

    private static void ReLoad(string[]? a)
    {
        var ms = typeof(Handler).GetMethods(BindingFlags.Static | BindingFlags.NonPublic | BindingFlags.DeclaredOnly);
        MethodDic = ms.ToDictionary(m => m.Name.ToLower(), m => m.CreateDelegate<Action<string[]>>());
    }
    private static void Help(string[]? a)
    {
        string text = File.ReadAllText($"{App.ApplicationBase}/语法.txt");
        Console.WriteLine(text);
    }

    private static void Version(string[]? a)
    {
        Console.WriteLine(App.Setting.Version);
    }

}
